package cn.edu.scau.cmi.zhuanglinting.hibernate.DAO;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.luyicheng.hibernate.domain.Student;
import cn.edu.scau.cmi.luyicheng.hibernate.domain.Teacher;

public class TeacherDAO {

	private static Configuration configuration;

	private static SessionFactory factory;

	private static Session session;

	static {
		configuration = new Configuration();
		// configuration.configure().addClass(User.class);
		configuration.configure();
		factory = configuration.buildSessionFactory();
	}

	public Teacher findTeacherById(Integer id) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Teacher teacher = session.get(Teacher.class, id);
		transaction.commit();
		session.close();
		return teacher;
	}

	public List<Teacher> findTeacherByName(String teacherName) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Query query = session.createQuery("FROM Teacher Where name = ?1");
		query.setParameter(1, teacherName);
		List<Teacher> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}

	public void newTeacher(Teacher teacher) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.save(teacher);
		transaction.commit();
		session.close();
	}

	public void updateTeacher(Teacher teacher) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.update(teacher);
		transaction.commit();
		session.close();
	}

	public List<Teacher> findAllTeacher() {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Query query = session.createQuery("FROM Teacher");
		List<Teacher> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}

	public void deleteTeacher(Teacher teacher) {
		StudentDAO studentDAO = new StudentDAO();
		Set<Student> studentSet = teacher.getStudentSet();
		for (Student student : studentSet) {
			student.setTeacher(null);
			studentDAO.updateStudent(student);
		}
		teacher.setStudentSet(null);
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.delete(teacher);
		transaction.commit();
		session.close();
	}
}
